package com.elinshaw.pattern.readwritelock;

public class ReadLock implements Lock {

    private final ReadWriteLockImpl readWriteLock;

    public ReadLock(ReadWriteLockImpl readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    @Override
    public void lock() throws InterruptedException {
        Object monitor = readWriteLock.getMUTEX();
        synchronized (monitor) {
            while (readWriteLock.getWritingWriters() > 0
                    || (readWriteLock.isPreferWriter() && readWriteLock.getWaitingWriters() > 0)) {
                monitor.wait();
            }
            readWriteLock.setReadingReaders(readWriteLock.getReadingReaders() + 1);
        }
    }

    @Override
    public void unLock() {
        Object monitor = readWriteLock.getMUTEX();
        synchronized (monitor) {
            readWriteLock.setReadingReaders(readWriteLock.getReadingReaders() + 1);
            //write线程获得更多机会
            readWriteLock.setPreferWriter(true);
            monitor.notifyAll();
        }
    }

}
